<template>
  <div class="left-component">
    <div class="profile-section">
      <div class="avatar-upload" @click="triggerFileInput">
        <img :src="this.personalInfo.user.avatarUrl "  :key="avatarKey" alt="profile" class="profile-image" />
        <div class="upload-overlay">
          <i class="el-icon-upload"></i>
          <span>更换头像</span>
        </div>
      </div>
      <input
          type="file"
          ref="fileInput"
          style="display: none"
          @change="handleAvatarChange"
          accept="image/*"
      >
      <div class="profile-info">
          <el-descriptions class="profile-descriptions"  :column="1" border>
            <el-descriptions-item label="姓名">{{ personalInfo.user.name }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ personalInfo.user.email }}</el-descriptions-item>
          </el-descriptions>
        <el-descriptions class="profile-descriptions"  :column="2" border>
          <el-descriptions-item label="年龄">{{ personalInfo.user.age }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ personalInfo.user.gender }}</el-descriptions-item>
        </el-descriptions>
        <!-- <div class="group-info">

          <div class="group-item">
            <span>{{ personalInfo.myParticipation }}</span>
            <h5>我的参与</h5>
          </div>

          <div class="group-item">
            <span>{{ personalInfo.myManagement }}</span>
            <h5>我的管理</h5>
          </div>

        </div> -->


      </div>
      <el-divider border-style="dashed" />
      <el-button type="warning" size="small" @click="updateUserInfo">修改信息</el-button>
    </div>
    <div class="recent-footprints" >
      <h4>最近足迹</h4>
      <ul>
        <li v-for="footprint in footprints" :key="footprint.footprintId">
          <el-link type="primary" @click="navigateToClub(footprint.clubId)">
            {{ footprint.clubName }} - {{ footprint.browseTime }}
          </el-link>
        </li>
      </ul>
      <el-pagination
          background
          layout="prev, pager, next"
          :total="totalFootprints"
          :page-size="pageSize"
          :pager-count="5"
          @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <div class="bottom-button">
      <el-button type="warning" size="large" @click="createClub">创建新社团</el-button>
    </div>

    <!-- 创建新社团表单 -->
    <el-dialog v-model="createClubDialogVisible" title="创建新社团" width="500px">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="社团logo" prop="clubLogo" required>
          <input type="file" @change="handleFileChange" />
        </el-form-item>
        <el-form-item label="社团名称" prop="clubName" required>
          <el-input v-model="form.clubName"></el-input>
        </el-form-item>
        <el-form-item label="社团介绍" prop="descriptionContent" required>
          <el-input type="textarea" v-model="form.descriptionContent"></el-input>
        </el-form-item>
        <el-form-item label="社团类型" prop="category" required>
          <el-select v-model="form.category" placeholder="请选择">
            <el-option label="学科技术类" value="学科技术类"></el-option>
            <el-option label="文艺体育类" value="文艺体育类"></el-option>
            <el-option label="公益服务类" value="公益服务类"></el-option>
            <el-option label="职业发展类" value="职业发展类"></el-option>
            <el-option label="国际交流类" value="国际交流类"></el-option>
            <el-option label="创新创业类" value="创新创业类"></el-option>
            <el-option label="娱乐休闲类" value="娱乐休闲类"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加入条件" prop="requirements" required>
          <el-input v-model="form.requirements"></el-input>
        </el-form-item>
        <el-form-item label="社团社区开放范围" prop="postPublicScopeEnum" required>
          <el-select v-model="form.postPublicScopeEnum" placeholder="请选择">
            <el-option label="全部人员可见" value="UserVisible"></el-option>
            <el-option label="社内人员可见" value="MembersVisible"></el-option>
            <el-option label="社内管理人员可见" value="AdminVisible"></el-option>
            <el-option label="隐藏" value="Hidden"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="warning" plain @click="createClubDialogVisible = false">取消</el-button>
        <el-button type="warning" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>

    <!-- 创建个人信息表单 -->
    <el-dialog v-model="editDialogVisible" title="修改个人信息" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editForm">
        <el-form-item label="姓名" prop="name" required>
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="editForm.age" type="number"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender" required>
          <el-select v-model="editForm.gender" placeholder="请选择">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
            <el-option label="保密" value="保密"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="warning" plain @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdate">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script>
import axios from 'axios';
import { ElLoading, ElNotification } from 'element-plus';

export default {
  name: "LeftComponent",
  props: {
    personalInfo: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      uploadHeaders: {
        Authorization: localStorage.getItem('token')
      },
      avatarUrl: this.personalInfo.user.avatarUrl,
      avatarKey: 0,
      // 创建新社团
      createClubDialogVisible: false,
      form: this.getInitialFormData(),
      rules: {
        clubLogo: [
          { required: true, message: "请上传社团logo", trigger: "change" },
        ],
        clubName: [
          { required: true, message: "请输入社团名称", trigger: "blur" },
          { max: 15, message: "名字太长", trigger: "blur" }
        ],
        descriptionContent: [
          { required: true, message: "请输入社团介绍", trigger: "blur" },
        ],
        category: [
          { required: true, message: "请选择社团类型", trigger: "change" },
        ],
        requirements: [
          { required: true, message: "请输入加入条件", trigger: "blur" },
        ],
        postPublicScopeEnum: [
          { required: true, message: "请选择社团社区开放范围", trigger: "change" },
        ]
      },
      editRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { max: 10, message: '姓名太长', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'change' },
          { type: 'number', min: 0, max: 500, message: '年龄必须在 0-500 之间', trigger: 'change' },
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ]
      },

      profileImage: require("../../assets/profile.jpg"), // 替换为实际路径
      footprints: [],
      totalFootprints: 0,
      pageSize: 5, // 每页显示的记录数
      currentPage: 1, // 当前页码

      editDialogVisible: false,
      editForm: {
        name: this.personalInfo.user.name,
        age: this.personalInfo.user.age,
        gender: this.personalInfo.user.gender
      }
    };
  },
  methods: {
    getInitialFormData() {
      return {
        clubLogo: "",
        clubName: "",
        clubType: "",
        openScope: "",
        joinCondition: "",
        clubDescription: "",
      };
    },
    navigateToClub(clubId) {
      this.$router.push({ name: "ClubDetail", query: { clubId: clubId } });
    },
    createClub() {
      this.form = this.getInitialFormData();
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
      this.createClubDialogVisible = true;
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file && this.beforeAvatarUpload(file)) {
        this.form.clubLogo = file;
      }
    },

    // 提交创建社团表单
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {

          const isLoading = this.$loading({
            lock: true,
            text: '正在提交创建社团申请...',
            background: 'rgba(0, 0, 0, 0.7)',
          });

          try {
            const formData = new FormData();
            formData.append('clubName', this.form.clubName);
            formData.append('descriptionContent', this.form.descriptionContent);
            formData.append('category', this.form.category);
            formData.append('requirements', this.form.requirements);
            formData.append('logoPicture', this.form.clubLogo);
            formData.append('postPublicScopeEnum', this.form.postPublicScopeEnum);

            const response = await axios.post('/club/createNewClub', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
              }
            });

            if (response.data.code === 0) {
              this.$message.success("申请已提交！");
              this.createClubDialogVisible = false;
            } else {
              // this.$message.error(response.data.message);

              ElNotification({
                title: '创建社团失败',
                message: response.data.message || "未知错误",
                type: 'error',
                dangerouslyUseHTMLString: true,
              })
            }
          } catch (error) {
            console.error("Error creating club:", error);
            this.$message.error("创建社团失败，请重试。");
          }

          isLoading.close();
        } else {
          console.log("表单验证未通过");
          return false;
        }
      });
    },
    triggerFileInput() {
      this.$refs.fileInput.click();
    },

    handleAvatarChange(event) {
      const file = event.target.files[0];
      if (file && this.beforeAvatarUpload(file)) {
        this.uploadAvatar(file);
      }
    },

    async uploadAvatar(file) {

      const isLoading = ElLoading.service({
        lock: true,
        text: '上传中...',
        background: 'rgba(0, 0, 0, 0.7)',
      });

      const formData = new FormData();
      formData.append('avatar', file);
      try {
        const response = await axios.put('/user/changeAvatar', formData);
        if (response.data.code === 0) {
          this.$message.success('头像上传成功');
          // 更新个人信息中的头像URL
          this.personalInfo.user.avatarUrl = response.data.data.avatarUrl;
          //刷新页面
          window.location.reload();
        } else {
          this.$message.error(response.data.message || '头像上传失败');
        }
      } catch (error) {
        console.error('Error uploading avatar:', error);
        this.$message.error('头像上传失败，请重试');
      }
      isLoading.close();
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return (isJPG || isPNG) && isLt2M;
    },
    async fetchFootprints(pageNum = 1) {
      try {
        const response = await axios.get('/footprint/getPersonalFootprint', {
          params: {pageNum, pageSize: this.pageSize}
        });
        if (response.data.code === 0) {
          this.footprints = response.data.data.records;
          this.totalFootprints = response.data.data.total;
        } else {
          console.error("Failed to fetch footprints:", response.data.message);
        }
      } catch (error) {
        console.error("Error fetching footprints:", error);
      }
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchFootprints(page);
    },

    async updateUserInfo() {
      this.editDialogVisible = true;
    },

    async submitUpdate() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await axios.put('/user/updateUserInfo', {
              name: this.editForm.name,
              age: this.editForm.age,
              gender: this.editForm.gender
            }, {
              headers: {
                Authorization: localStorage.getItem('token')
              }
            });

            if (response.data.code === 0) {
              this.$message.success('用户信息更新成功');
              this.personalInfo.user.name = this.editForm.name;
              this.personalInfo.user.age = this.editForm.age;
              this.personalInfo.user.gender = this.editForm.gender;
              this.editDialogVisible = false;
            } else {
              this.$message.error(response.data.message || '用户信息更新失败');
            }
          } catch (error) {
            console.error('Error updating user info:', error);
            this.$message.error('用户信息更新失败,请重试');
          }
        } else {
          console.log('表单验证未通过');
          return false;
        }
      });
    }
  },
  mounted() {
    this.fetchFootprints(this.currentPage);
  }
};
</script>


<style scoped>
.left-component {
  display: flex;
  flex-direction: column;
  padding: 25px;
  background-color: #fdfdfd;
  border-radius: 10px;
  width: 400px;
  height: 650px;
}

.profile-section {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.profile-image {
  border-radius: 50%;
  width: 100px;
  height: 100px;
  margin-bottom: 10px;
}

.profile-info h4 {
  margin-bottom: 10px;
  font-size: 1.2rem;
}

.group-info {
  display: flex;
  justify-content: space-around;
  width: 100%;
  margin-top: 10px;
  flex-direction: row;
  gap: 20px; /* 在 flex 项目之间添加间距 */
}

.group-item {
  text-align: center;
}

.group-item span {
  display: block;
  font-size: 1.5rem;
  font-weight: bold;
}

.recent-footprints {
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.recent-footprints h4 {
  margin-bottom: 15px;
  font-size: 1.2rem;
}

.recent-footprints ul {
  list-style: none;
  padding: 0;
}

.recent-footprints ul li {
  margin-bottom: 10px;
}

.el-link {
  font-size: 1rem;
}

.bottom-button {
  display: flex;
  justify-content: center;
  margin-top: auto;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  margin-top: 10px;
}

/* 对话框样式调整 */
.el-dialog {
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.el-dialog__header {
  border-bottom: 1px solid #e8e8e8;
  padding: 15px 20px;
}

.el-dialog__title {
  font-size: 1.2rem;
  font-weight: bold;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  border-top: 1px solid #e8e8e8;
  padding: 15px 20px;
  text-align: right;
}

.el-button {
  padding: 10px 20px;
  border-radius: 5px;
  font-size: 1rem;
}

.el-button--warning {
  background-color: #ffc107;
  border-color: #ffc107;
  color: #fff;
}

.el-button--warning:hover {
  background-color: #ffca28;
  border-color: #ffca28;
}

.el-button--warning.is-plain {
  background-color: #fff;
  border-color: #ffc107;
  color: #ffc107;
}

.el-button--warning.is-plain:hover {
  background-color: #ffc107;
  color: #fff;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-size: 1rem;
  color: #333;
}

.el-input,
.el-select,
.el-textarea {
  width: 100%;
}

.el-input__inner,
.el-select__inner,
.el-textarea__inner {
  border-radius: 5px;
  padding: 10px;
  font-size: 1rem;
}

.el-upload {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.avatar-upload {
  position: relative;
  cursor: pointer;
}

.upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 50%;
}

.avatar-upload:hover .upload-overlay {
  opacity: 1;
}

.upload-overlay i {
  color: white;
  font-size: 24px;
  margin-bottom: 5px;
}

.upload-overlay span {
  color: white;
  font-size: 14px;
}
.el-pagination {
  display: flex;
  justify-content: center;
  margin: 20px;
}
</style>
